// 第3题：以三元组表作为稀疏矩阵的存储结构，实现两个矩阵的加减运算，
// 运算结果以矩阵形式输出。要求：输入 m、n、k1、k2，随机生成稀疏矩阵，
// 矩阵大小为m×n，k1、k2为非零元素个数。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <malloc.h>
#define MAXSIZE 100
typedef struct {
    int data, row, col;
}triple;
typedef struct {
    triple data[MAXSIZE+1];
    int row, col, total;
}Matrix;
void randomInit(Matrix& m, int nums, int row, int col) {
    m.row = row;
    m.col = col;
    m.total = nums;
    int* temp = (int*)malloc(sizeof(int) * nums);
    int c = 0;
    while (c < nums) {
        int t = rand() % (row * col);
        bool repeat = false;
        for (int i = 0; i < c; ++i) {
            if (temp[i] == t) {
                repeat = true;
                break;
            }
        }
        if (repeat) {
            --c;
        } else {
            temp[c++] = t;
        }
    }
    for (int i = 0; i < nums; ++i) {
        m.data[i].row = temp[i] / col;
        m.data[i].col = temp[i] % col;
        m.data[i].data = rand() % 99 + 1;
    }
}
void add(Matrix a, Matrix b, Matrix& cm) {
    int row = a.row, col = a.col, nums = a.total;
    cm.row = row;
    cm.col = col;
    int ctotal = 0;
    for (int r = 0; r < row; ++r) {
        for (int c = 0; c < col; ++c) {
            int s = 0, t;
            for (t = 0; t < a.total; ++t) {
                if (r == a.data[t].row && c == a.data[t].col) {
                    s += a.data[t].data;
                    break;
                }
            }
            for (t = 0; t < b.total; ++t) {
                if (r == b.data[t].row && c == b.data[t].col) {
                    s += b.data[t].data;
                    break;
                }
            }
            if (s) {
                cm.data[ctotal].data = s;
                cm.data[ctotal].row = r;
                cm.data[ctotal].col = c;
                ++ctotal;
            }
        }
    }
    cm.total = ctotal;
}
void show(Matrix m) {
    for (int r = 0; r < m.row; ++r) {
        for (int c = 0; c < m.col; ++c) {
            int t;
            for (t = 0; t < m.total; ++t) {
                if (r == m.data[t].row && c == m.data[t].col) {
                    printf("%2d ", m.data[t].data);
                    break;
                }
            }
            if (t == m.total)
                printf(" 0 ");
        }
        printf("\n");
    }
    printf("\n");
}
int main(void) {
    Matrix a, b;
    int row, col, k1, k2;
    scanf("%d%d%d%d", &row, &col, &k1, &k2);
    srand(time(0));
    randomInit(a, k1, row, col);
    randomInit(b, k2, row, col);
    show(a);
    show(b);
    Matrix c;
    add(a, b, c);
    show(c);

    return 0;
}